<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.questionStem" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入题目名称查询"></el-input>
      <el-input v-model="data.courseName" style="width: 240px; margin-right: 10px" placeholder="请输入课程名称查询"></el-input>
      <el-input v-model="data.teacherName" style="width: 240px; margin-right: 10px" placeholder="请输入教师名称查询"></el-input>
      <el-select v-model="data.typeName" style="width: 240px; margin-right: 10px" placeholder="全部" @change="load">
        <el-option label="全部" :value="''"></el-option>
        <el-option v-for="type in data.typeData" :key="type.id" :label="type.typeName" :value="type.typeName"></el-option>
      </el-select>

      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button  type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="questionStem" label="题目名称" show-overflow-tooltip/>
        <el-table-column prop="courseName" label="课程名称" show-overflow-tooltip/>
        <el-table-column prop="teacherName" label="授课教师" width="120"/>
        <el-table-column prop="typeId" label="题型" width="100">
          <template v-slot="scope">
            <el-tag v-if="scope.row.typeId === 1" type="success">{{ scope.row.typeName }}</el-tag>
            <el-tag v-if="scope.row.typeId === 2" type="primary">{{ scope.row.typeName }}</el-tag>
            <el-tag v-if="scope.row.typeId === 3" type="warning">{{ scope.row.typeName }}</el-tag>
            <el-tag v-if="scope.row.typeId === 4" type="info">{{ scope.row.typeName }}</el-tag>
            <el-tag v-if="scope.row.typeId === 5" type="danger">{{ scope.row.typeName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分数" width="80"/>
        <el-table-column label="选项">
          <template v-slot="scope">
            <span v-if="scope.row.hasOptions === 0">无</span>
            <div v-else>
              <div v-for="(option, index) in scope.row.options" :key="index">{{ option.optionLabel }}. {{ option.optionValue }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="answer" label="答案" show-overflow-tooltip/>
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <el-dialog title="题目信息" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="courseId" label="选择课程">
          <el-select v-model="data.form.courseId" placeholder="请选择课程">
            <el-option
                v-for="item in data.courseData"
                :key="item.id"
                :label="item.courseName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="questionStem" label="题目名称">
          <el-input v-model="data.form.questionStem" placeholder="请输入题目名称"></el-input>
        </el-form-item>
        <el-form-item prop="typeId" label="选择题型">
          <el-select v-model="data.form.typeId" placeholder="请选择题型" @change="onTypeChange">
            <el-option
                v-for="item in data.typeData"
                :key="item.id"
                :label="item.typeName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="score" label="分数">
          <el-input-number v-model="data.form.score" :min="0" :max="100" placeholder="请输入题目分数"></el-input-number>
        </el-form-item>
        <el-form-item prop="answer" label="题目答案" v-if="data.form.hasOptions === 1">
          <el-input v-model="data.form.answer" placeholder="请输入题目答案（多选答案用英文逗号隔开）"></el-input>
        </el-form-item>
        <el-form-item prop="options" label="选项" v-if="data.form.hasOptions === 1">
          <div v-for="(option, index) in data.form.options" :key="index" style="display: flex; align-items: center; margin-bottom: 10px;">
            <!-- 显示选项字母和对应的选项内容 -->
            <el-input
                style="width: 80px; margin-right: 10px;"
                v-model="option.optionLabel"
                :placeholder="'选项 ' + String.fromCharCode(65 + index)">
            </el-input>
            <el-input
                style="flex-grow: 1;"
                v-model="option.optionValue"
                :placeholder="'请输入 ' + String.fromCharCode(65 + index) + ' 的内容'">
            </el-input>

            <!-- 删除按钮 -->
            <el-button
                v-if="data.form.options.length > 2"
                @click="removeOption(index)"
                size="small"
                type="danger"
                icon="el-icon-delete"
                style="margin-left: 10px;">
              删除
            </el-button>
          </div>

          <!-- 动态添加选项按钮 -->
          <el-button
              @click="addOption"
              size="small"
              type="primary"
              style="margin-top: 0;">
            添加选项
          </el-button>
        </el-form-item>

        <!-- 简答题和填空题无需选项，统一处理答案 -->
        <el-form-item prop="answer" label="题目答案" v-if="data.form.hasOptions === 0">
          <el-input v-model="data.form.answer" placeholder="请输入题目答案"></el-input>
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item prop="questionImg" label="题目图片">
          <el-upload
              :action="baseUrl + '/files/upload'"
              list-type="picture-card"
              :file-list="data.form.questionImg"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :on-success="handleFileSuccess"
              multiple>
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogImageUrlVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue";

const baseUrl = import.meta.env.VITE_BASE_URL;

const data = reactive({
  user: JSON.parse(localStorage.getItem('user') || '{}'),
  formVisible: false,
  form: {
    id: null,  // 添加 id 字段用于修改时区分
    typeId: null,
    courseId: null,
    questionStem: "",
    answer: "",
    options: [],
    hasOptions: 0,
    questionImg: []  // 用于存储上传的图片URL
  },
  tableData: [],
  pageNum: 1,
  pageSize: 8,
  total: 0,
  questionStem: null,
  ids: [],
  courseData: [],
  typeData: [],
  dialogImageUrl: '',
  dialogImageUrlVisible: false,
});

const onTypeChange = (value) => {
  const selectedType = data.typeData.find(item => item.id === value);
  data.form.hasOptions = selectedType ? selectedType.hasOptions : 0;

  // 初始化选项
  if (data.form.hasOptions === 1) {
    // 默认添加两个选项
    data.form.options = [
      {optionLabel: "A", optionValue: ""},
      {optionLabel: "B", optionValue: ""},
    ];
  } else {
    data.form.options = [];
  }
};

// 动态添加选项
const addOption = () => {
  const nextLabel = String.fromCharCode(65 + data.form.options.length); // 获取下一个选项的字母
  data.form.options.push({optionLabel: nextLabel, optionValue: ""});
};

// 删除选项
const removeOption = (index) => {
  if (data.form.options.length > 2) {  // 确保至少保留两个选项
    data.form.options.splice(index, 1);
  } else {
    ElMessage.warning("至少保留两个选项");
  }
};

const loadCourse = () => {
  request.get('/course/selectAll', {
    params: {
      teacherId: data.user.id
    }
  }).then(res => {
    if (res.code === '200') {
      data.courseData = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const loadType = () => {
  request.get('/questionType/selectAll').then(res => {
    if (res.code === '200') {
      data.typeData = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const load = () => {
  request.get('/question/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      questionStem: data.questionStem,
      courseName: data.courseName,  // 新增课程名称查询
      teacherName: data.teacherName, // 新增教师名称查询
      typeName: data.typeName,      // 新增题型名称查询
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || [];
      data.total = res.data?.total;
    }
  });
};

const handleAdd = () => {
  data.form = {
    id: null,
    questionStem: "",
    typeId: null,
    courseId: null,
    answer: "",
    options: [],
    score: 0,
    hasOptions: 0,
    questionImg: []
  };  // 重置 form
  data.formVisible = true;
};

const handleEdit = (row) => {
  data.form = {...row};
  // 将 questionImg 转换为 el-upload 需要的格式
  if (Array.isArray(data.form.questionImg)) {
    data.form.questionImg = data.form.questionImg.map(imgUrl => ({url: imgUrl}));
  } else {
    data.form.questionImg = [];
  }
  data.formVisible = true;
};

const save = () => {
  // 将 questionImg 转换回字符串数组
  const formData = {...data.form};
  formData.questionImg = formData.questionImg.map(file => file.url);

  formData.id ? update(formData) : add(formData);
};

const add = (formData) => {
  request.post('/question/add', formData).then(res => {
    if (res.code === '200') {
      ElMessage.success("保存成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const update = (formData) => {
  request.put('/question/update', formData).then(res => {
    if (res.code === '200') {
      ElMessage.success("保存成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const del = (id) => {
  ElMessageBox.confirm("确定删除此题目?", "提示", {
    type: "warning"
  }).then(() => {
    request.delete(`/question/delete/${id}`).then(res => {
      if (res.code === "200") {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};

const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning("请选择要删除的题目");
    return;
  }
  ElMessageBox.confirm("确定批量删除选中的题目?", "提示", {
    type: "warning"
  }).then(() => {
    request.post(`/question/deleteBatch`, {ids: data.ids}).then(res => {
      if (res.code === "200") {
        ElMessage.success("批量删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};

const reset = () => {
  data.questionStem = null;
  data.courseName = null;  // 重置课程名称查询
  data.teacherName = null; // 重置教师名称查询
  data.typeName = null;    // 重置题型名称查询
  load();
};

const handleSelectionChange = (val) => {
  // 处理选中的数据
  console.log(val); // 打印选中的行
  data.ids = val.map(item => item.id); // 假设你要存储选中行的 ID
};

const handleRemove = (file, fileList) => {
  data.form.questionImg = fileList.map(file => ({url: file.url}));
};

const handlePictureCardPreview = (file) => {
  data.dialogImageUrl = file.url;
  data.dialogImageUrlVisible = true;
};

const handleFileSuccess = (response, file, fileList) => {
  data.form.questionImg.push({url: response.data}); // 将返回的图片URL添加到列表中
};

const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
  }
  return isImage;
};

// 初始化课程和题型数据
loadCourse();
loadType();
load();
</script>

<style>
/* 样式优化 */
.el-input {
  margin-right: 10px; /* 给选项的输入框右边添加一些间距 */
}

.el-button {
  margin-top: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>



